package cc.z8g.browser.core.download;

import android.app.Activity;
import android.app.DownloadManager;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.webkit.URLUtil;

import androidx.annotation.NonNull;

import java.net.HttpURLConnection;
import java.net.URL;

import cc.z8g.browser.R;
import cc.z8g.browser.dialog.BrowserDialog;
import cc.z8g.browser.utils.HttpUtils;
import cc.z8g.browser.utils.SystemServiceManager;
import cc.z8g.browser.utils.ThreadPool;
import cc.z8g.browser.utils.MiscUtils;

/**
 * Handle download requests
 */
public class DownloadHandler {

    public static void download(@NonNull Activity activity, @NonNull DownloadRequest download) {
        String urlStr = download.getUrl();
        // 第一步，先根据url获取下载地址(有的会有多次重定向，即 headers 下的"Location"指向的 url ，需要网络库去自动处理一下)
        // 第二步，code 可用才交给系统下载器
        ThreadPool.postIO(() -> {
            try {
                URL url = new URL(urlStr);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.connect();

                if (activity.isDestroyed()) {
                    return;
                }

                String disposition = conn.getHeaderField("Content-Disposition");
                String type = conn.getContentType();
                if (type == null) {
                    type = conn.getHeaderField("Mime-type");
                }
                final String filename = URLUtil.guessFileName(urlStr, disposition, type);

                int contentLength = conn.getContentLength();
                String title = activity.getString(R.string.download_save_title) + (contentLength <= 0 ? "" : "(" + HttpUtils.formatSize(contentLength) + ")");
                ThreadPool.postUI(() -> {
                    BrowserDialog.showEditText(activity, title, filename, filename, R.string.download_save_ok, s -> {
                        startBySystemDownloader(urlStr, filename);
                        return null;
                    });
                });
            } catch (Exception e) {
                MiscUtils.showToast(activity, activity.getString(R.string.download_failed) + " " + e.getMessage());
            }
        });
    }

    private static void startBySystemDownloader(@NonNull String url, @NonNull String filename) {
        DownloadManager downloadManager = SystemServiceManager.INSTANCE.getDownloadManager();
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        // 设置标题和描述等
        request.setTitle(filename);
        request.setDescription(R.string.download_started + filename);
        // 设置下载目录和文件名
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename.replaceAll("/", ""));
        request.setVisibleInDownloadsUi(true); // 设置可见性
        long downloadId = downloadManager.enqueue(request);
    }
}
